<template>
	<view class="embodiment-setting">
		<view class="name">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm">
				<u-form-item label="真实姓名" prop="form.name" ref="item1" labelWidth="150rpx" :borderBottom="false">
					<u--input v-model="form.name" border="none" placeholder="请填写真实姓名"></u--input>
				</u-form-item>
			</u--form>
		</view>
		<view class="wechat-code">
			<view>
				请上传微信收款码（仅首次需要）
			</view>
			<view>
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="1" uploadIcon="plus"></u-upload>
			</view>
		</view>
		<view class="alipay-code">
			<view>
				请上传支付宝收款码（仅首次需要）
			</view>
			<view>
				<u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" multiple
					:maxCount="1" uploadIcon="plus"></u-upload>
			</view>
		</view>
		<view class="name">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="uForm">
				<u-form-item label="银行账号" prop="form.bank_account" labelWidth="150rpx" :borderBottom="false">
					<u--input v-model="form.bank_account" border="none" placeholder="请填写银行账号"></u--input>
				</u-form-item>
				<u-form-item label="开户行" prop="form.bank_branch" labelWidth="150rpx" :borderBottom="false">
					<u--input v-model="form.bank_branch" border="none" placeholder="请填写开户行"></u--input>
				</u-form-item>
			</u--form>
		</view>
		<view class="btn">
			<button class="comfirm" @click="submitPaymentInfo">确定</button>
		</view>
	</view>
</template>

<script>
import { BASE_URL } from '@/util/api';
import { cleanUrl, completeUrl } from '@/util/urlHelper';

export default {
	data() {
		return {
			form: {
				name: '',
				bank_account: '',
				bank_branch: ''
			},
			wechat_image: '',
			alipay_image: '',
			fileList1: [],
			fileList2: [],
			rules: {
				'name': {
					type: 'string',
					required: true,
					message: '请填写姓名',
					trigger: ['blur', 'change']
				},
				'bank_account': {
					type: 'string',
					required: true,
					message: '请填写银行账号',
					trigger: ['blur', 'change']
				},
				'bank_branch': {
					type: 'string',
					required: true,
					message: '请填写开户行',
					trigger: ['blur', 'change']
				},
			},
		};
	},
	onLoad() {
		this.getpayment();
	},
	methods: {
		async getpayment() {
			const launchFlag = uni.getStorageSync('my_info');
			const res = await this.$myRuquest({
				url: '/index/api/getpayset',
				data: {
					"uid": launchFlag.id,
				},
			})

			if (res.data.code == 200) {
				this.form.name = res.data.data.bank_name;
				// 使用completeUrl确保展示时有完整URL
				this.wechat_image = completeUrl(res.data.data.wechat_image);
				this.alipay_image = completeUrl(res.data.data.alipay_image);
				this.form.bank_account = res.data.data.bank_account;
				this.form.bank_branch = res.data.data.bank_branch;

				this.fileList1 = this.wechat_image ? [{
					url: this.wechat_image,
					status: 'success',
					message: '',
				}] : [];

				this.fileList2 = this.alipay_image ? [{
					url: this.alipay_image,
					status: 'success',
					message: '',
				}] : [];
			}
		},
		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1)
		},

		async afterRead(event) {
			let lists = [].concat(event.file)
			let fileListLen = this[`fileList${event.name}`].length
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				try {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					const completeUrlResult = completeUrl(result);
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: completeUrlResult
					}))
					fileListLen++

					// 根据上传的图片类型设置对应的image变量
					if (event.name === '1') {
						this.wechat_image = completeUrlResult;
					} else if (event.name === '2') {
						this.alipay_image = completeUrlResult;
					}
				} catch (error) {
					console.error('上传失败:', error);
					this[`fileList${event.name}`][fileListLen].status = 'failed';
					this[`fileList${event.name}`][fileListLen].message = '上传失败';
				}
			}
		},

		uploadFilePromise(filePath) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: BASE_URL + '/index/api/upload',
					filePath: filePath,
					name: 'file',
					success: (uploadRes) => {
						try {
							const res = JSON.parse(uploadRes.data);
							if (res.code === 200) {
								// 确保返回的是相对路径
								let url = res.url || res.path;
								if (url.startsWith('http')) {
									url = cleanUrl(url);
								}
								resolve(url);
							} else {
								reject(new Error(res.message || '上传失败'));
							}
						} catch (e) {
							reject(new Error('解析响应数据失败'));
						}
					},
					fail: (error) => {
						reject(error);
					}
				});
			});
		},

		async submitPaymentInfo() {
			const launchFlag = uni.getStorageSync('my_info');

			// 提交前清理URL，确保不重复
			const submitData = {
				"uid": launchFlag.id,
				"wechat_image": cleanUrl(this.wechat_image),
				"alipay_image": cleanUrl(this.alipay_image),
				"bank_account": this.form.bank_account,
				"bank_name": this.form.name,
				"bank_branch": this.form.bank_branch,
			};

			const res = await this.$myRuquest({
				url: '/index/api/payment_info',
				data: submitData,
			})

			if (res.data.code == 200) {
				uni.showToast({
					title: '保存成功',
					icon: 'success',
					duration: 2000
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 2000);
			}
		}
	}
}
</script>

<style lang="scss">
.embodiment-setting {
	padding: 0 16rpx;

	&>view {
		margin-bottom: 20rpx;
		border-radius: 20rpx;
	}

	.name,
	.wechat-code,
	.alipay-code {
		padding: 0 20rpx;
		background: #fff;
	}

	.wechat-code,
	.alipay-code {
		padding: 20rpx 20rpx;

		view {
			margin-bottom: 20rpx;
		}
	}
}

.btn {
	margin-top: 50rpx;
	padding: 0 16rpx;

	button {
		margin-bottom: 20rpx;
		background-color: #05b80e;
		color: #fff;
	}
}
</style>